<template>
  <div>
    <Title title="我的班级" />
    <div class="class">
      <div class="inp fx" v-if="!info.id">
        <el-input placeholder="请输入班级口令" v-model="word"></el-input>
        <el-button class="btn" @click="addClass">加入</el-button>
      </div>
      <div class="info">
        <el-empty
          description="你还没有加入班级哦, 快加入班级吧"
          v-if="!info.id"
        ></el-empty>
        <div class="wrap" v-else>
          <el-descriptions title="班级信息">
            <el-descriptions-item label="班级id">{{
              info.id
            }}</el-descriptions-item>
            <el-descriptions-item label="班级名字">{{
              info.name
            }}</el-descriptions-item>
            <el-descriptions-item label="老师">{{
              info.user.name
            }}</el-descriptions-item>
            <el-descriptions-item label="创建时间">{{
              info.create_time
            }}</el-descriptions-item>
          </el-descriptions>
          <el-button @click="exit">退出班级</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Title from "@/components/common/Title";
import { addClass, getStuClass, exitStuClass } from "@/api/class";
import { error, warn, success, formatTime } from "@/utils";
export default {
  data() {
    return {
      word: "",
      info: {},
    };
  },
  methods: {
    async addClass() {
      // 没有班级
      if (!this.word) return warn("请输入班级口令!!");
      const res = await addClass(this.word);
      if (res.code === 1) {
        success(res.msg)
        this.getData()
        this.word = ""
      } else {
        error(res.msg);
      }
    },
    /**
     * 退出班级
     */
    async exit() {
      const classId = this.info.id
      if (classId) {
        const res = await exitStuClass(classId)
        if (res.code === 1) {
          success(res.msg)
          this.getData()
        } else {
          warn(res.msg)
        }
      }
    },
    /**
     * 获取班级信息
     */
    async getData() {
      const res = await getStuClass();
      if (res.data.length) {
        formatTime(res.data);
        this.info = res.data[0];
      } else {
        this.info = {}
      }
    },
  },
  created() {
    this.getData();
  },
  components: {
    Title,
  },
};
</script>

<style lang="scss" scoped>
.btn {
  margin-left: 20px;
}

.info {
  margin-top: 30px;
  padding: 10px;
  background-color: #fff;
}
</style>
